package priv.mill.db;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class XMLUtils {
	private static final String ENCODING = "utf-8";

	public static <T> T formXML(Class<T> clazz, String xml) throws JAXBException, UnsupportedEncodingException {
		JAXBContext jaxbContext = null;
		T object = null;
		if (xml != null && !"".equals(xml)) {
			// 获取入口类
			jaxbContext = JAXBContext.newInstance(clazz);
			// 将xml装入内存，注意编码，别忘了系统的默认编码是(GBK)
			ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xml.getBytes(ENCODING));
			// 获取xml到对象的转换器
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			// 转换
			JAXBElement<T> jaxbElement = unmarshaller.unmarshal(new StreamSource(byteArrayInputStream), clazz);
			object = (T) jaxbElement.getValue();// 获取转换结果
		}
		return object;
	}
	
	public static <T> T formClassPathXML(Class<T> clazz, String fileName) throws JAXBException, UnsupportedEncodingException {
		JAXBContext jaxbContext = null;
		T object = null;
		if (fileName != null && !"".equals(fileName)) {
			// 获取入口类
			jaxbContext = JAXBContext.newInstance(clazz);
			// 获取xml到对象的转换器
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			
			InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
			// 转换
			JAXBElement<T> jaxbElement = unmarshaller.unmarshal(new StreamSource(in), clazz);
			object = (T) jaxbElement.getValue();// 获取转换结果
		}
		return object;
	}
	
	public static void main(String[] args) throws Exception {
		Config config = formClassPathXML(Config.class, "db.xml");
		System.out.println(config.getDriver());

	}

	public static <T> String toXML(T object) throws JAXBException, UnsupportedEncodingException {
		String xml = "";
		JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
		Marshaller marshaller = jaxbContext.createMarshaller();
		// 是否格式化生成xml
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		// 设置编码方式
		marshaller.setProperty(Marshaller.JAXB_ENCODING, ENCODING);

		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		marshaller.marshal(object, byteArrayOutputStream);
		byte[] buf = byteArrayOutputStream.toByteArray();
		xml = new String(buf, 0, buf.length, ENCODING);
		return xml;
	}
}
